#include <tsin/runtime/Enemy.hpp>

#include <tsin/library/EnemyEvent.hpp>

#include <tsin/library/GameViewport.hpp>
#include <tsin/display/DecoratedImage.hpp>

#include <cstring>

#include <tsin/util/MemCheck.hpp>
using namespace tsin;

Enemy::Enemy()
{
        memset(events, 0, MAX_EVENTS * sizeof(EnemyEvent *));
        nrEvents = 0;
        image = 0;
}

Enemy::~Enemy()
{
        for (int i = 0; i < MAX_EVENTS; i++)
                delete events[i];
        if (image)
                delete image;
}

bool Enemy::addEvent(EnemyEvent *event)
{
        if (nrEvents == MAX_EVENTS)
                return false;

        for (int i = 0; i < MAX_EVENTS; i++)
                if (events[i] == 0) {
                        events[i] = event;
                        nrEvents ++;
                        break;
                }

        return true;
}

void Enemy::checkEvents(bool early)
{
        for (int i = 0, n = 0; i < MAX_EVENTS, n < nrEvents; i++) {
                if (events[i] == 0)
                        continue;
                if (events[i]->trigger(*this, early))
                        events[i] = events[i]->handle(*this, early);
                (events[i] == 0) ? (nrEvents --) : (n ++);
        }
}

